package com.bee.beemanage.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bee.beemanage.api.entity.output.MenuTree;
import com.bee.beemanage.api.service.SysMenuService;
import com.bee.beemanage.api.entity.SysMenu;
import com.bee.beemanage.api.entity.SysRoleMenu;
import com.bee.beemanage.api.mapper.SysMenuMapper;
import com.bee.beemanage.api.mapper.SysRoleMenuMapper;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultTool;
import com.bee.beemanage.system.common.utils.transaction.TransUtils;
import com.bee.beemanage.system.common.utils.transaction.Transaction;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author 陈国松
 * @since 2022-10-27
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Resource
    SysMenuMapper sysMenuMapper;
    @Resource
    SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public List<MenuTree> selectMenuTreeByUserId(String userId, String type) {
        List<SysMenu> sysMenus = new ArrayList<>();
        if(null==userId){
            //查询所有菜单信息，并构建菜单树
            if(null!=type){
                QueryWrapper<SysMenu> query = Wrappers.query();
                List<String> typeList = new ArrayList<>();
                typeList.add(type);
                typeList.add("0");
                query.orderByDesc("order_num");
                query.in("type",typeList);
                sysMenus = sysMenuMapper.selectList(query);
            }else{
                sysMenus = sysMenuMapper.selectList(null);
            }
        }else{
            //查到用户拥有的所有菜单
            sysMenus = sysMenuMapper.selectListByUserId(userId);
        }

        List<MenuTree> ResultTree = new ArrayList<MenuTree>();

        //找到没有上级菜单的菜单
        List<SysMenu> RootMenus = sysMenus.stream().filter(sysMenu -> null==sysMenu.getParentId())
                .collect(Collectors.toList());
        for (SysMenu rootMenu : RootMenus) {
            //构建成菜单树的结构
            MenuTree menuTree = new MenuTree();
            BeanUtils.copyProperties(rootMenu, menuTree);
            ResultTree.add(menuTree);
        }
        getChildren(sysMenus, ResultTree);
        return ResultTree;
    }

    /**
     * 根据用户id查询用户拥有的菜单
     *
     * @param userId
     */
    @Override
    public List<SysMenu> selectMenuButtonByUserId(String userId) {
        List<SysMenu> sysMenus = sysMenuMapper.selectListByUserId(userId);
        return sysMenus.stream().filter(sysMenu -> null != sysMenu.getType()
                && "2".equals(sysMenu.getType())).collect(Collectors.toList());
    }

    /**
     * 根据id删除菜单同时删除掉角色菜单关联信息
     *
     * @param Id 菜单id
     */
    @Override
    public Result deleteMenuById(String Id) {
        Result result = ResultTool.success();
        Transaction trans = null;
        try {
            trans = TransUtils.getTrans();
            trans.begin();
            sysMenuMapper.deleteById(Id);
            QueryWrapper<SysRoleMenu> query = Wrappers.query();
            query.eq("menu_Id",Id);
            sysRoleMenuMapper.delete(query);
            trans.commit();
        } catch (Exception e) {
            if(null!=trans){
                trans.rollback();
            }
            result = ResultTool.fail();
            result.setErrorMsg(e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * 递归构建菜单树
     * @param SysMenus
     * @param MenuTrees
     */
    public void getChildren(List<SysMenu> SysMenus,List<MenuTree> MenuTrees){
        //遍历根节点
        for (MenuTree menuTree : MenuTrees) {
            List<SysMenu> Childrens = SysMenus.stream().filter(sysMenu ->
                    (sysMenu.getParentId()!=null&&sysMenu.getParentId().equals(menuTree.getId())))
                    .collect(Collectors.toList());
            if(Childrens.size()!=0){
                List<MenuTree> TmpMenuTreeList = new ArrayList<MenuTree>();
                for (SysMenu children : Childrens) {
                    MenuTree TmpmenuTree = new MenuTree();
                    BeanUtils.copyProperties(children, TmpmenuTree);
                    TmpMenuTreeList.add(TmpmenuTree);
                }
                menuTree.setChildren(TmpMenuTreeList);
                getChildren(SysMenus,TmpMenuTreeList);
            }
        }
    }
}
